<?php

namespace app\common\model;

use app\common\library\utils\RandomUtils;
use think\Model;

/**
 * Agent
 */
class Agent extends Model
{
    // 表名
    protected $name = 'haipi_agent';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;


    public function admin(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Admin::class, 'admin_id', 'id');
    }

    public function getInviteUrlAttr($value, $data){
        return get_sys_config('url', 'web')."?invite_code=" . $data['invite_code'] ;
    }

    public static function onBeforeInsert($model): void{
        $model->invite_code = self::genUniCode();
    }


    public static function genUniCode()
    {
       
        do {
            $code = RandomUtils::getRandomCode(4, 3);
            $code = strtoupper($code);
            $exists = self::where('invite_code', $code)->count() > 0;
        } while ($exists);
        return $code;
    }
}